import React, { Component } from 'react';
import { toJS } from 'mobx';
import equals from 'deep-equal';
import { observer, inject } from 'mobx-react';
import { withRouter, Route } from 'react-router-dom';
import { Icon, Popover, ActivityIndicator, Result, Tools, PhotoSwipe, Avatar } from 'weaver-mobile';
import { ListViewPage, TabPage, RouteLayout, Reply } from 'weaver-mobile-page';
import ChanceCard from '../card/Chance';
import CustomerCard from '../card/Customer';
import ContacterCard from '../card/Contacter';
import ContactListStore from '../../stores/list/ContactListStore';
import ContactRemarkItems from './../list/ContactRemarkItems'
const Item = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
const getLabel = Tools.getLabel;
const leftConfig = [
  { type: 'voice' },
  { type: 'blog-tupian' },
  { type: 'tianjia' },
];
const separator = (sectionID, rowID) => (
  <div
    key={`${sectionID}-${rowID}`}
    style={{
      backgroundColor: '#f3f7fe',
      height: 10,
      borderTop: '0px solid #ECECED',
      borderBottom: '0px solid #ECECED',
    }}
  />
);
// @inject('contactListStore')
@withRouter
@observer
export default class ContactList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      store: new ContactListStore(),
      overlay: [
        (<Item key="4" value="scan" data-seed="logId">Scan</Item>),
        (<Item key="5" value="special" style={{ whiteSpace: 'nowrap' }}>My Qrcode</Item>),
        (<Item key="6" value="button ct">
          <span style={{ marginRight: 5 }}>Help</span>
        </Item>),
      ],
      span: [7, 1],
      curParams: { chanceId: "", customerId: "" },
      curChanceId: "",
      curCustomerId: "",
      curContacterId: "",
      customHeight: undefined
    };
  }

  componentWillMount() {
    const { params, match } = this.props;
    const ps = params ? params : match.params;
    this.state.store.doNew(this, ps);
  }

  componentDidMount() {
    // this.props.contactListStore.doInit();
    this.state.store.doInit();
    this.props.onRef && this.props.onRef(this);
  }

  componentWillReceiveProps(nextProps) {
    if (this.props.showAddContact) {
      this.addContact();
      return;
    }
    let tp = { ...this.props.params };
    let np = { ...nextProps.params };
    if (tp._ec_ismobile) {
      eval("delete tp._ec_ismobile");
    }
    if (tp.ismobile) {
      eval("delete tp.ismobile");
    }
    if (np._ec_ismobile) {
      eval("delete np._ec_ismobile");
    }
    if (np.ismobile) {
      eval("delete np.ismobile");
    }
    for (let k in tp) {
      if (tp[k] === "") {
        eval("delete tp." + k);
      }
    }
    for (let k in np) {
      if (np[k] === "") {
        eval("delete np." + k);
      }
    }
    // console.log("tp",tp);
    // console.log("np",np);
    if (!equals(tp, np)) {
      np.ismobile = 1;
      np._ec_ismobile = true;
      this.state.store.params = np;
      this.state.store.doSearch();
    }
  }

  componentWillUnmount() {
    // this.props.contactListStore.doClear();
    this.state.store.doClear();
  }

  render() {
    // const store = this.props.contactListStore;
    const { store } = this.state;
    const { initResponsed, initSuccessed, initFailedMsg, replyStore, remarkStore } = store;

    if (initResponsed) {
      if (initSuccessed) {
        const { list, showCheck, createContactLayout, params, showOutInput, photoFiles, photoIndex, photoVisible, relatedChanceLayout, relatedContacterLayout, relatedCustomerLayout, setRemark, saveRemarkCmd } = store;
        const { span, overlay, visible, curParams, curCustomerId, curChanceId, curContacterId, customHeight } = this.state;

        let listViewPageProps = {};
        listViewPageProps.showCheck = showCheck;
        listViewPageProps.store = list;
        listViewPageProps.customHeight = customHeight;
        listViewPageProps.getTemplate = this.getTemplate;
        listViewPageProps.renderSeparator = separator;
        // if(store.params.rightType){
        //   listViewPageProps.heightSpace = 50;
        // }
        return (
          <div className="crm-list-content">
            <div className="crm_reply_mask">
              <Reply
                wrappedComponentRef={ref => {
                  if (ref) {
                    store.replyRef = ref;
                  }
                }}
                placeholder={getLabel("84370", "请填写联系记录")}
                store={replyStore}
                leftConfig={leftConfig}
                // showOutInput={showOutInput}
                onSubmit={datas => store.saveReply(datas)}
                onMaskClick={() => {
                  store.replyStore.doClear();
                }}
              />
            </div>
            <div className="crm_reply_mask">
              <Reply
                wrappedComponentRef={ref => this.replyRef = ref}
                placeholder={getLabel("386312", "请输入评论内容")}
                store={remarkStore}
                // leftConfig={leftConfig}
                // showOutInput={showOutInput}
                onSubmit={datas => { console.log(datas); setRemark(datas); saveRemarkCmd() }}
              />
            </div>
            <div className="crm_contact_list">
              <ListViewPage.Normal {...listViewPageProps} />
            </div>
            <PhotoSwipe
              items={photoFiles}
              index={photoIndex}
              visible={photoVisible}
              onClose={this.closePhoto.bind(this)}
            />
            <Route
              key={relatedCustomerLayout.id}
              path={relatedCustomerLayout.path}
              render={() => {
                // 客户卡片
                let detailContent = <CustomerCard params={{ id: curCustomerId }} />
                return (
                  <RouteLayout getContainer={() => document.getElementById("root")}>
                    <div
                      key="relatedChanceLayout"
                      className="wm-route-layout"
                    >
                      {detailContent}
                    </div>
                  </RouteLayout>
                )
              }}
            />
            <Route
              key={relatedChanceLayout.id}
              path={relatedChanceLayout.path}
              render={() => {
                // 商机卡片
                let detailContent = <ChanceCard params={{ id: curChanceId }} />
                return (
                  <RouteLayout getContainer={() => document.getElementById("root")}>
                    <div
                      key="relatedChanceLayout"
                      className="wm-route-layout"
                    >
                      {detailContent}
                    </div>
                  </RouteLayout>
                )
              }}
            />
            <Route
              key={relatedContacterLayout.id}
              path={relatedContacterLayout.path}
              render={() => {
                // 联系人卡片
                let detailContent = <ContacterCard params={{ id: curContacterId }} />
                return (
                  <RouteLayout getContainer={() => document.getElementById("root")}>
                    <div
                      key="relatedContacterLayout"
                      className="wm-route-layout"
                    >
                      {detailContent}
                    </div>
                  </RouteLayout>
                )
              }}
            />
          </div>
        );
      } else {
        return (
          <div>
            <Result
              img={<Icon type="cross-circle-o" className="crm_commerce_initFailedMsg" style={{ fill: '#F13642' }} />}
              title=""
              message={initFailedMsg}
            />
          </div>);
      }
    } else {
      return <div className="crm-bg-loading"><ActivityIndicator text="Loading..." /></div>;
    }
  }

  getTemplate = (template) => {
    const newTemp = {
      default: [{
        key: 'col_1',
        render: (rowData) => {
          // const store = this.props.contactListStore;
          // console.log("rowData",rowData);
          const { store } = this.state;
          const { relatedChanceLayout, relatedContacterLayout, relatedCustomerLayout } = store;
          let { hasChanceAuthspan,id, workplanid, avatorspan, createridspan, descriptionspan, imgs, imgsspan, workplanidspan, attachs, sellchanceid, contacterid, sellchancename, contactername, createdate, createtime, begindate, createrid, begintime, crmid, crmidspan, label } = rowData;
        //  console.log(hasChanceAuthspan)
        //  if(hasChanceAuthspan=="false") return;
          let imgsArea = [];
          let imgArr = [];
          const flag = "remark_" + id;
          if (imgs != "") {
            imgs = imgsspan;
            imgArr = imgs.split(",");
            let photoFiles = [];
            for (const imgId of imgArr) {
              let imgObj = {};
              imgObj.id = imgId;
              imgObj.name = "";
              imgObj.fileExtendName = "";
              imgObj.showDelete = false;
              imgObj.url = "/weaver/weaver.file.FileDownload?fileid=" + imgId + "";
              photoFiles.push(imgObj);
            }
            let imgWidth = "";
            let x = 0;// 每行显示几张图片
            if (imgArr.length == 1) {
              imgWidth = "100%";
              let styleObj = {};
              styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[0] + "')";
              styleObj.width = imgWidth;
              styleObj.paddingBottom = imgWidth;
              // imgsArea.push(<div className="crm-zoom-div" key={workplanid}><div className="crm-zoom-image" style={styleObj} onClick={()=>store.showPhotos(0,photoFiles)}></div></div>);
              imgsArea.push(<div className="crm-zoom-div" key={workplanid}><div className="crm-zoom-image" style={styleObj} onClick={() => { PhotoSwipe.showImage(photoFiles, 0); }}></div></div>);
            } else if (imgArr.length == 2 || imgArr.length == 4) {
              x = 2;
              let rowCount = imgArr.length / x;
              for (let j = 0; j < rowCount; j++) {
                imgWidth = "48%";
                let imgsInner = [];
                for (let k = j * x; k < j * rowCount + x; k++) {
                  let styleObj = {};
                  styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[k] + "')";
                  styleObj.width = imgWidth;
                  styleObj.paddingBottom = imgWidth;
                  if (j > 0) {
                    styleObj.marginTop = "3%";
                  }
                  // imgsInner.push(<div className="crm-zoom-image" key={imgArr[k]} style={styleObj} onClick={()=>store.showPhotos(k,photoFiles)}></div>);
                  imgsInner.push(<div className="crm-zoom-image" key={imgArr[k]} style={styleObj} onClick={() => { PhotoSwipe.showImage(photoFiles, k); }}></div>);
                }
                imgsArea.push(<div className="crm-zoom-div" key={workplanid + "_" + j}>{imgsInner}</div>);
              }
            } else {
              x = 3;
              let rowCount = parseInt(imgArr.length % x == 0 ? imgArr.length / x : imgArr.length / x + 1);
              for (let j = 0; j < rowCount; j++) {
                imgWidth = "30%";
                let imgsInner = [];
                for (let k = j * x; k < j * x + x; k++) {
                  let styleObj = {};
                  styleObj.width = imgWidth;
                  styleObj.paddingBottom = imgWidth;
                  if (j > 0) {
                    styleObj.marginTop = "4%";
                  }
                  if (k >= imgArr.length) {
                    imgsInner.push(<div className="crm-zoom-image" key={"img_" + k} style={styleObj}></div>);
                  } else {
                    styleObj.backgroundImage = "url('/weaver/weaver.file.FileDownload?fileid=" + imgArr[k] + "')";
                    // imgsInner.push(<div className="crm-zoom-image" key={imgArr[k]} style={styleObj} onClick={()=>store.showPhotos(k,photoFiles)}></div>);
                    imgsInner.push(<div className="crm-zoom-image" key={imgArr[k]} style={styleObj} onClick={() => { PhotoSwipe.showImage(photoFiles, k); }}></div>);
                  }
                }
                imgsArea.push(<div className="crm-zoom-div" key={workplanid + "_" + j}>{imgsInner}</div>);
              }
            }
          }
          let customerArea = [];
          if (crmid && crmidspan) {
            customerArea.push(<div className="crm-related-wrapper" key={"customerArea" + id + "_" + crmid}>
              <div className="crm-related-left">
                {getLabel("783", "相关客户")}&nbsp;{":"}&nbsp;
            </div>
              <div className="crm-related-right">
                <div className="crm_phone" onClick={() => {
                  this.setState({ curCustomerId: crmid });
                  this.props.history.push(relatedCustomerLayout.path);
                }}>
                  {crmidspan}
                </div>
              </div>
            </div>);
          }
          let chanceArea = [];
          if (sellchanceid != "" && sellchancename != "") {
            chanceArea.push(<div className="crm-related-wrapper" key={"chanceArea_" + id + "_" + sellchanceid}>
              <div className="crm-related-left">
                {getLabel("84372", "相关商机")}&nbsp;{":"}&nbsp;
              </div>
              <div className="crm-related-right">
                <div className="crm_phone" onClick={() => {
                  this.setState({ curChanceId: sellchanceid });
                  this.props.history.push(relatedChanceLayout.path);
                }}>
                  {sellchancename}
                </div>
              </div>
            </div>);
          }
          let contacterArea = [];
          if (contacterid != "" && contactername != "") {
            contacterArea.push(<div className="crm-related-wrapper" key={"contacterArea_" + id + "_" + contacterid}>
              <div className="crm-related-left">
                {getLabel("84373", "相关联系人")}&nbsp;{":"}&nbsp;
              </div>
              <div className="crm-related-right">
                <div className="crm_phone" onClick={() => {
                  this.setState({ curContacterId: contacterid });
                  this.props.history.push(relatedContacterLayout.path);
                }}>
                  {contactername}
                </div>
              </div>
            </div>);
          }
          let contactWay = [];
          if (label != "") {
            contactWay.push(<div className="crm-related-wrapper" key={"contacterArea_" + id + "_" + contacterid}>
              <div className="crm-related-left">
                {getLabel(15858, "联系方式")}&nbsp;{":"}&nbsp;
              </div>
              <div className="crm-related-right">
                {label}
              </div>
            </div>);
          }
          return (
            <div>
              <div className="crm-flex-wrapper">
                <div className="crm-flex-left">
                  <Avatar userId={createrid} />
                </div>
                <div className="crm-flex-right">
                  <div dangerouslySetInnerHTML={{ __html: createridspan }} />
                </div>
              </div>
              <div style={{ marginTop: "3px" }} dangerouslySetInnerHTML={{ __html: descriptionspan.replace(/&lt;/g, "<").replace(/&gt;/, ">")  }} />
              {customerArea}
              {chanceArea}
              {contacterArea}
              {contactWay}
              <div dangerouslySetInnerHTML={{ __html: workplanidspan }} />
              {imgsArea}
              <div style={{ display: "flex", height: "22px" }} className="crm-contact-footer">
                <span style={{ color: "#b3a6b3" }}>{begindate}&nbsp;{begintime}</span>
                <div style={{ display: "flex", margin: "0 0 0 auto" }}>
                  <div style={{ cursor: "pointer", flex: "1 1", textAlign: "right", color: "#555555" }}
                    onClick={(e) => { this.onReplyClick({ workPlanId: id, parentId: 0, receiver: createrid, customer: crmid, contacterid: contacterid, sellchanceid }, this[flag].state.store); e.stopPropagation(); }}>
                    <Icon type="blog-comment" />
                    <div style={{ height: "18px", lineHeight: "22px", verticalAlign: "middle", float: "right", cursor: "pointer", marginLeft: "5px" }}>
                      {getLabel(675, "评论")}
                    </div>
                  </div>
                </div>
              </div>
              <ContactRemarkItems params={{ contactid: id }} onReplyClick={(params) => { this.onReplyClick({ ...params, customer: crmid, contacterid: contacterid, sellchanceid }, this[flag].state.store) }} onRef={(ref) => { this[flag] = ref; }} />
            </div>
          );
        },
      }],
    };
    return newTemp;
  }

  addContact() {
    // const store = this.props.contactListStore;
    const { store } = this.state;
    store.addContact();
  }

  doSearch() {
    const { store } = this.state;
    store.doSearch();
  }

  closePhoto() {
    // const store = this.props.contactListStore;
    const { store } = this.state;
    store.hidePhotos();
  }

  resetListHeight() {
    this.setState({ customHeight: "100%" });
    setTimeout(() => {
      this.setState({ customHeight: undefined });
    }, 10);
  }
  onReplyClick = (params, callback) => {
    const { store } = this.state;
    store.setRemark(params, callback);
    // console.log(params, callback)
    const replyRef = this.replyRef; // 避免某一瞬间找不到this.replyRef
    if (replyRef) {
      replyRef.setVisible(true, () => {
        replyRef.getInputFocus();
      });
    }
  }
}